package com.owen.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.owen.pojo.Fenlei;
import com.owen.pojo.Order;
import com.owen.pojo.Product;
import com.owen.pojo.User;
import com.owen.server.ProductServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.support.HttpAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/product")
public class ProductController {

    @Autowired
    private ProductServer productServer;

    @ResponseBody
    @RequestMapping(value = "/fileExport")
    public void fileExport(Product product, HttpServletResponse response) throws ClassNotFoundException, IndexOutOfBoundsException, IOException {
        // 生成excel
        ExcelWriter writer = ExcelUtil.getWriter();
        // 数据库查询
        List<Product> byProduct = productServer.findByProduct(product);
        List<Map<String, Object>> rows = byProduct.stream().map(item -> {
            Map<String, Object> maps = new HashMap<>();
            maps.put("id", item.getId() == null ? "" : item.getId().toString());
            maps.put("createtime", item.getCreatetime());
            maps.put("content", item.getContent());
            maps.put("name", item.getName());
            maps.put("price", item.getPrice() == null ? "" : item.getPrice().toString());
            maps.put("productlock", item.getProductlock());
            maps.put("fenleiid", item.getFenleiid());
            return maps;
        }).collect(Collectors.toList());

        // Title
        int columns = Class.forName("com.owen.pojo.Product").getDeclaredFields().length;
        writer.merge(columns - 1, "商品信息");
        // Header
        writer.addHeaderAlias("id", "主键ID");
        writer.addHeaderAlias("createtime", "上架日期");
        writer.addHeaderAlias("content", "商品分类名");
        writer.addHeaderAlias("name", "商品名");
        writer.addHeaderAlias("price", "单价");
        writer.addHeaderAlias("productlock", "是否购买");
        writer.addHeaderAlias("fenleiid", "商品分类ID");

        // Body
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 30);
        writer.setColumnWidth(4, 30);
        writer.setColumnWidth(5, 30);
        writer.setColumnWidth(6, 30);
        writer.write(rows, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("商品信息-" + DateUtil.today() + ".xls", "utf-8"));
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @ResponseBody
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    public String deleteBatch(Integer [] ids) {
        Map<String,Object> res = new HashMap<>();
        Integer count = productServer.deleteBatch(ids);
        if (count > 0) {
            res.put("code", 200);
            res.put("msg", "删除成功！");
        }else {
            res.put("code", 201);
            res.put("msg", "删除失败！");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public String findAll() {

        PageHelper.startPage(1, 10);
        List<Product> products = productServer.findAll();
        PageInfo<Product> productInfo = new PageInfo<>(products);
        Map<String, Object> res = new HashMap<>();
        if (products != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", productInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/findById", method = RequestMethod.GET)
    public String findById(Integer id) {
        Product product = productServer.findById(id);
        Map<String, Object> res = new HashMap<>();
        if (product != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", product);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id) {
        Integer count = productServer.deleteById(id);
        Map<String, Object> res = new HashMap<>();
        if (count > 0) {
            res.put("code", "200");
            res.put("msg", "删除成功");
        } else {
            res.put("code", "201");
            res.put("msg", "删除失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @RequestMapping(value = "/updateById", method = RequestMethod.POST)
    public String updateById(Product product) {
        Integer count = productServer.updateById(product);
        return "product/productlist";
    }

    @ResponseBody
    @RequestMapping(value = "/addProduct", method = RequestMethod.GET)
    public String addProduct(Product product, HttpSession session) {
        product.setProductlock("0");
        User user = (User)session.getAttribute("login");
        product.setFenleiid(user.getId().toString());
        Integer count = productServer.addProduct(product);
        Map<String, Object> res = new HashMap<>();
        if (count > 0) {
            res.put("code", "200");
            res.put("msg", "添加成功");
        } else {
            res.put("code", "201");
            res.put("msg", "添加失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/findByProduct", method = RequestMethod.GET)
    public String findByProduct(Product product, Integer xuanzhepage, String currentPage) {

        // 获取页数
        Integer current = 1;
        if (currentPage != null) {
            current = Integer.valueOf(currentPage);
        }

        PageHelper.startPage(current, xuanzhepage);
        List<Product> products = productServer.findByProduct(product);
        PageInfo<Product> pageInfo = new PageInfo<>(products);

        Map<String, Object> res = new HashMap<>();
        if (products != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", pageInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }


}